/**
 * Copyright (c) 2009 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.event.eventobj.EventObject;
import net.risesoft.risebi.collection.event.eventobj.SystemLogEventObj;
import net.risesoft.risebi.collection.model.Service;
import net.risesoft.risebi.collection.model.SystemLog;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.ContextUtil;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionInvocation;

/**
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/ServiceAction")
public class ServiceAction extends BaseAction implements Trimable{
	private static final long serialVersionUID = -4844369324910037998L;	
	private static Log log = LogFactory.getLog(ServiceAction.class);
	
	private ServiceManager serviceManager;

	@Action(value="prepareServiceList",
			results={@Result(name="success", location="/admin/service/serviceList.jsp")}
	)
	public String prepareServiceList() throws Exception {
		return SUCCESS;
	}
	
	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#afterTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public void afterTrim(ActionInvocation invocation) {
		
	}

	/**
	 * @see net.risesoft.commons.struts2extension.Trimable#preTrim(com.opensymphony.xwork2.ActionInvocation)
	 */
	public boolean preTrim(ActionInvocation invocation) {
		return true;
	}
	
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonList".equalsIgnoreCase(this.whichJson)){
				List<Service> lst = serviceManager.getObjects(Service.class);
				this.json = JSONUtil.getJsonString("include","guid,name,code,tabIndex",lst);
			}
		}catch(Exception e){
			log.error(ExceptionUtil.transformException(e));
			this.json = "[]";
		} 

		return AJAX;
	}

	@Action(value="insertOrUpdate")
	public String insertOrUpdate() throws Exception {
		User user = this.getSessionUser();
		
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Service[] serviceList = (Service[])JSONUtil.stringToArray(json, Service.class);
			for (Service s : serviceList){
				boolean newed = false;
				if(s.getGuid()==null || s.getGuid().trim().length()==0 || s.getGuid().startsWith("NEW")){
					s.setGuid(new GUID().toString());
					newed = true;
				}
				
				//TODO:应该排重
				serviceManager.saveObject(s);
				
//        		记录日志
        		SystemLog systemLog = new SystemLog();
        		if(newed)
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_ADD);
        		else
        			systemLog.setOpterateType(SystemLog.OPTERATETYPE_EDIT);
        		systemLog.setUser(user);
        		
        		EventObject systemLogEventObject = new SystemLogEventObj(this);
        		Map systemLogMap = new HashMap();
        		systemLogMap.put("systemLog", systemLog);
        		if(newed)
        			systemLogMap.put("keyName", "serviceadd");
        		else
        			systemLogMap.put("keyName", "serviceedit");
        		systemLogMap.put("service", s);
        		
        		systemLogEventObject.setDataMap(systemLogMap);
        		ContextUtil.getAc().publishEvent(systemLogEventObject);
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			log.error(ExceptionUtil.transformException(e));
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}

	@Action(value="remove")
	public String remove() throws Exception {
		User user = this.getSessionUser();
		
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Service service = (Service) serviceManager.getObject(Service.class, node);
			
			serviceManager.removeObject(Service.class, node);
			
//    		记录日志
    		SystemLog systemLog = new SystemLog();
    		systemLog.setOpterateType(SystemLog.OPTERATETYPE_REMOVE);
    		systemLog.setUser(user);
    		
    		EventObject systemLogEventObject = new SystemLogEventObj(this);
    		Map systemLogMap = new HashMap();
    		systemLogMap.put("systemLog", systemLog);
    		systemLogMap.put("keyName", "serviceremove");
    		systemLogMap.put("service", service);
    		
    		systemLogEventObject.setDataMap(systemLogMap);
    		ContextUtil.getAc().publishEvent(systemLogEventObject);
			
			ldb.set("success", true);
			ldb.set("reason", "删除服务成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;		
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
}
